package com.sctvcloud.zhaohua_sd.ui.activities;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.media.ThumbnailUtils;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.google.gson.JsonArray;
import com.gridsum.tracker.GridsumWebDissector;
import com.jiongbull.jlog.JLog;
import com.luck.picture.lib.PictureExternalPreviewActivity;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.tools.PictureFileUtils;
import com.ruihang.generalibrary.ui.dialog.BaseDialogFragment;
import com.ruihang.generalibrary.ui.util.OnItemInternalClick;
import com.ruihang.generalibrary.ui.widget.CustomCheckBox;
import com.ruihang.generalibrary.ui.widget.CustomFontEditText;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.ruihang.generalibrary.utils.ListUtils;
import com.ruihang.generalibrary.utils.SharedPreferencesUtil;
import com.sctvcloud.zhaohua_sd.R;
import com.sctvcloud.zhaohua_sd.application.Cache;
import com.sctvcloud.zhaohua_sd.application.Constances;
import com.sctvcloud.zhaohua_sd.base.BaseActivity;
import com.sctvcloud.zhaohua_sd.beans.FUsers;
import com.sctvcloud.zhaohua_sd.beans.RebllionCommitResult;
import com.sctvcloud.zhaohua_sd.beans.SingleResult;
import com.sctvcloud.zhaohua_sd.beans.TopicContent;
import com.sctvcloud.zhaohua_sd.http.AbsNetCallBack;
import com.sctvcloud.zhaohua_sd.http.NetUtils;
import com.sctvcloud.zhaohua_sd.http.ParamsEditor;
import com.sctvcloud.zhaohua_sd.ui.adapter.RebllionCommitAdapter;
import com.sctvcloud.zhaohua_sd.ui.dialog.ConfirmDialogFragment;
import com.sctvcloud.zhaohua_sd.ui.dialog.PicChoiceDiaFragment;
import com.sctvcloud.zhaohua_sd.ui.dialog.ProtocolFragment;
import com.sctvcloud.zhaohua_sd.ui.dialog.RebllionDiaFragment;
import com.sctvcloud.zhaohua_sd.ui.dialog.ShotChoiceDiaFragment;
import com.sctvcloud.zhaohua_sd.ui.fragment.RebllionFragment;
import com.sctvcloud.zhaohua_sd.ui.utils.PermissionUtils;
import com.sctvcloud.zhaohua_sd.ui.utils.PictureUtils;
import com.sctvcloud.zhaohua_sd.ui.utils.SkipUtil;
import com.sctvcloud.zhaohua_sd.ui.utils.TitleUtils;
import com.sctvcloud.zhaohua_sd.ui.utils.UIUtils;
import com.sctvcloud.zhaohua_sd.ui.utils.UiListMarginUtils;
import com.sctvcloud.zhaohua_sd.utils.GaoDeLocationUtil;
import com.sctvcloud.zhaohua_sd.utils.LocalUtils;
import com.sctvcloud.zhaohua_sd.utils.UserManager;
import com.sctvcloud.zhaohua_sd.utils.VideoCompressAsyncTask;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.io.File;
import java.io.FileOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import wseemann.media.FFmpegMediaMetadataRetriever;

import static com.sctvcloud.zhaohua_sd.application.Constances.REBLLION_KEY;

/**
 * 民生诉求提交页
 */
public class ApplyCommitActivity extends BaseActivity implements RebllionCommitAdapter.RemainListSize, TextWatcher ,CompoundButton.OnCheckedChangeListener, GaoDeLocationUtil.LocationChangeListener{
    @BindView(R.id.title_top_edit_topic)
    protected CustomFontTextView publish;
    @BindView(R.id.rebllion_commit_content)
    protected CustomFontEditText rebllion_commit;
    @BindView(R.id.rebllion_commit_type_title)
    protected CustomFontTextView type_cv;
    @BindView(R.id.rebllion_commit_address_title)
    protected CustomFontTextView addree_cv;
    @BindView(R.id.rebllion_commit_pic_list)
    protected RecyclerView pic_list;
    @BindView(R.id.rebllion_commit_prompt)
    protected CustomFontTextView prompt;

    @BindView(R.id.id_flowlayout)
    protected TagFlowLayout flowlayout;
    @BindView(R.id.ck_annoy)
    protected CustomCheckBox push_cb;

    @BindView(R.id.rebllion_commit_title)
    protected CustomFontEditText rebllion_commit_title;
    @BindView(R.id.rebllion_commit_contact)
    protected CustomFontEditText rebllion_commit_contact;
    @BindView(R.id.tv_rules)
    protected TextView tv_rules;
    @BindView(R.id.title_top_logo_layout)
    protected LinearLayout title_top_logo_layout;
    @BindView(R.id.title_top_title)
    protected CustomFontTextView title_top_title;
    @BindView(R.id.tv_depart)
    protected CustomFontTextView tv_depart;


    private RebllionDiaFragment rebllionDiaFragment;
    private PicChoiceDiaFragment picChoiceDiaFragment;
    private ShotChoiceDiaFragment shotChoiceDiaFragment;
    private RebllionCommitAdapter adapter;
    private GridLayoutManager manger;
    private List<LocalMedia> selectList = new ArrayList<>();

    private Handler mHandler;
    private int maxSelectNum = 9;
    private int type = TYPE_CAMERA_PIC;  //type为0 拍照 1 录像 2图片
    private int rebellionType = Constances.REBELLION_TYPE_BREAKING_NEWS;
    private List<LocalMedia> currentList = new ArrayList<>();
    private int themeId;
    private boolean isLongClick = true;
    private String mVideoCoverImage;
    private int mLocationState = 0; //0正在定位，1定位成功，2定位失败
    private long mLocationTime = 0;
    private PermissionUtils mPermissionUtils;
    public static final int REQUEST_CODE = 8;
    public static final String REBLLION_TAG = "dia_rebllion_fragment";
    public static final String PIC_TAG = "dia_pic_choice_fragment";
    public static final String SHOT_TAG = "dia_shot_choice_fragment";
    public static final String PROTOCOL_TAG = "protocol";

    public static final String VALS = "vals";

    public static final int TYPE_CAMERA_PIC = 0;
    public static final int TYPE_VIDEO = 1;
    public static final int TYPE_PIC = 2;
    private String coverImageUrl;
    private JsonArray images;
    private Handler compressHandler;
    private boolean isCompressing = false;
    private boolean isInCurrentPage = false;
    private LayoutInflater mInflater;
    private ArrayList<TopicContent> mVals = new ArrayList<>();
    private int mPageNo = 0;
    private int mPageAll = 0;
    private final static int pageSize = 10;
    TagAdapter<TopicContent> tagAdapter;
    private TopicContent tp;
    private int locateFailTimes = 0;
    private ProtocolFragment protocolFragment;
    protected static final int BRANCH = 100;
    int branchId;
    String branchName;
    private String compressPath = "";//视频压缩后的地址
    private boolean isCompressSuccess = true;
    private boolean isPublishing = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new TitleUtils(this);
        themeId = R.style.picture_default_style;
        mHandler = new Handler();
        compressHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (null != msg) {
                    int what = msg.what;
                    switch (what) {
                        case VideoCompressAsyncTask.COMPRESS_SUCCESS:
                            isCompressing = false;
//                            closeProgress();
                            toast("压缩成功");
//                            SingleToast.getInstance(RebllionCommitActivity.this).showCenterToast("压缩成功");
                            compressPath = (String) msg.obj;
                            isCompressSuccess = true;
                            uploadVideo();
                            break;
                        case VideoCompressAsyncTask.COMPRESS_ERROR:
//                            closeProgress();
                            toast("压缩失败");
//                            SingleToast.getInstance(RebllionCommitActivity.this).showCenterToast("视频压缩失败，请重试");
                            compressPath = (String) msg.obj;
                            isCompressing = false;
                            isCompressSuccess = false;
                            uploadVideo();
                            break;
                    }
                }
            }
        };

        mVals = (ArrayList<TopicContent>) getIntent().getSerializableExtra(VALS);

        if(null != mVals && mVals.size()>0) {
            mVals.remove(0);
        }

        initView();
    }

    @Override
    protected void initInject() {
        setContentView(R.layout.activity_apply_commit);
        ButterKnife.bind(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isPublishing) {
            showProgress(getString(R.string.rebllion_publish_wait), true);
        }else  if(isCompressing){
            showProgress("视频处理中，请勿退出或关闭屏幕"  , true);
        }
        isInCurrentPage = true;
    }

    @Override
    protected void onPause() {
        super.onPause();
        closeProgress();
        isInCurrentPage = false;
    }


//    @Override
//    public void onBackPressed() {
//        if(!isCompressing) {
//                    super.onBackPressed();
//            RebllionCommitActivity.this.finish();
//        }
//
//    }

    private void initView() {

        title_top_logo_layout.setVisibility(View.GONE);
        title_top_title.setVisibility(View.VISIBLE);
        title_top_title.setText(getText(R.string.tv_add));


        tv_rules.setText(Html.fromHtml("<font color=\"#989898\">" + getResources().getString(R.string.text_rules) + "</font>"+
                "<font color=\"#358BFF\">" +getResources().getString(R.string.text_rules_item_1) + "</font>" +"<br>"+"<font color=\"#989898\">"+getResources().getString(R.string.show_after_audit)+ "</font>"+"<br>"));
        publish.setVisibility(View.VISIBLE);
        publish.setText(getString(R.string.rebllion_publish));
        publish.setBackgroundDrawable(getResources().getDrawable(R.drawable.live_banner_title_tip_bg));

        manger = new GridLayoutManager(this, 3);
        pic_list.setItemAnimator(new DefaultItemAnimator());
        manger.setSmoothScrollbarEnabled(true);
        manger.setAutoMeasureEnabled(true);
        pic_list.setHasFixedSize(true);
        pic_list.setNestedScrollingEnabled(false);
        pic_list.setLayoutManager(manger);
        new UiListMarginUtils().setMargin(this, pic_list, R.dimen.item_list_large_margin_left, R.dimen.item_list_large_margin_right);
        int type = getIntent().getIntExtra(RebllionFragment.EX_TYPE, -1);
        if (type > 0) {
            selectList = (ArrayList<LocalMedia>) getIntent().getSerializableExtra(EX_DATA);
            if (selectList != null) {
                currentList.addAll(selectList);
                prompt.setVisibility(View.GONE);
            }

        }
        adapter = new RebllionCommitAdapter(this, selectList).setItemInternalClick(picItemClick).setRemainListSize(this);
        adapter.setOnLongItemClick(onLongClick);
        pic_list.setAdapter(adapter);
        rebllion_commit.addTextChangedListener(this);
        rebellionType = (int) SharedPreferencesUtil.getParam(this, REBLLION_KEY, 1);
        refreshRebellionType();
        refreshLocationState(null);
        checkLocationPermission();

        mInflater = LayoutInflater.from(this);

        tagAdapter = new TagAdapter<TopicContent>(mVals)
        {

            @Override
            public View getView(FlowLayout parent, int position, TopicContent s)
            {
                TextView tv = (TextView) mInflater.inflate(R.layout.flow_text,
                        flowlayout, false);
                tv.setText(s.getTopicContent());
                return tv;
            }
            @Override
            public boolean setSelected(int position, TopicContent s)
            {
                return false;
            }
        };

        flowlayout.setAdapter(tagAdapter);
        flowlayout.setOnTagClickListener(new TagFlowLayout.OnTagClickListener()
        {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent)
            {
                return true;
            }
        });

        flowlayout.setOnSelectListener(new TagFlowLayout.OnSelectListener()
        {
            @Override
            public void onSelected(Set<Integer> selectPosSet)
            {
                if(null !=selectPosSet && selectPosSet.size()>0){
                    for(Integer i: selectPosSet){
                        tp = tagAdapter.getItem(i);
                    }
                }else{
                    tp = null;
                }

            }

        });


    }

    @OnClick(value = {R.id.rebllion_commit_type, R.id.title_top_edit_topic, R.id.rebllion_commit_address_title,R.id.tv_rules,R.id.li_depart})
    public void rebllionClick(View view) {
        ArrayList<Pair<String, String>> pairs = new ArrayList<>();
        pairs.add(new Pair<>("页面", "投稿"));
        switch (view.getId()) {
            case R.id.rebllion_commit_type:
                if (rebllionDiaFragment == null) {
                    rebllionDiaFragment = new RebllionDiaFragment();
                }
                pairs.add(new Pair<>("行为类型", "输入"));
                GridsumWebDissector.getInstance().trackEvent(this, "", "爆料类型", "", 200, pairs);
                rebllionDiaFragment.setCallBack(rebllionCallback);
                rebllionDiaFragment.show(getSupportFragmentManager(), REBLLION_TAG);
                break;
            case R.id.title_top_edit_topic:
                if (UserManager.getInstance().isLogin()) {




                    if (TextUtils.isEmpty(rebllion_commit.getText().toString())) {
                        toast(R.string.apply_publish_content_empty);
                        return;
                    }
                    if (rebellionType == Constances.REBELLION_TYPE_PIC_NEWS && (!ListUtils.isListValued(currentList) || PictureMimeType
                            .pictureToVideo(currentList.get(0).getPictureType()) != 1)) {
                        toast(R.string.rebllion_publish_img_empty);
                        return;
                    }
                    if (rebellionType == Constances.REBELLION_TYPE_VIDEO_NEWS && (!ListUtils.isListValued(currentList) || PictureMimeType
                            .pictureToVideo(currentList.get(0).getPictureType()) != 2)) {
                        toast(R.string.rebllion_publish_video_empty);
                        return;
                    }
                    if(!checkPhone() || !checkTitle()){
                        return;
                    }
                    if (TextUtils.isEmpty(branchName)) {
                        toast(R.string.rebllion_publish_branch_empty);
                        return;
                    }

                    pairs.add(new Pair<>("行为类型", "输入"));
                    GridsumWebDissector.getInstance().trackEvent(this, "", "发布", "", 200, pairs);
                    uploadData();

                } else {
                    Intent intent = new Intent(this, LoginActivity.class);
                    startActivity(intent);
                }
                break;
            case R.id.rebllion_commit_address_title:
                if (mLocationState == 0) {
                    pairs.add(new Pair<>("行为类型", "输入"));
                    GridsumWebDissector.getInstance().trackEvent(this, "", "地点", "", 200, pairs);
                    checkLocationPermission();
                } else if (mLocationState == 2) {
                    checkLocationPermission();
                }
                break;
            case R.id.tv_rules:
                showProtocol();
                break;
            case R.id.li_depart:
                Intent intent = new Intent(this, DepartmentActivity.class);
                intent.putExtra("branchId",branchId);
                startActivityForResult(intent,BRANCH);
                break;
        }
    }



    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    selectList = PictureSelector.obtainMultipleResult(data);
                    Log.e("path", "==pic==" + selectList.toString() + selectList.size() + type);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                    // 如果裁剪并压缩了，已取压缩路径为准，因为是先裁剪后压缩的

                    if (type == TYPE_CAMERA_PIC) {
                        currentList.addAll(selectList);
                        selectList = currentList;
                        if (adapter.getEqualDatas() == selectList) {
                            adapter.notifyDataSetChanged();
                        } else {
                            adapter.setData(selectList);
                        }
                    } else if (type == TYPE_VIDEO) {
                        adapter.setData(selectList);
                        currentList.clear();
                        currentList.addAll(selectList);
//                        if (null != selectList && selectList.size() > 0 && !TextUtils.isEmpty(selectList.get(0).getPath())) {
//                            //压缩视频
//                            compressVideo(selectList.get(0));
//                        }
                    } else if (type == TYPE_PIC) {
                        adapter.setData(selectList);
                        currentList.clear();
                        currentList.addAll(selectList);
//                        if (null != selectList && selectList.size() > 0 && selectList.get(0).getPictureType().equalsIgnoreCase("video/mp4")
//                                && !TextUtils.isEmpty(selectList.get(0).getPath())) {
//                            //压缩视频
//                            compressVideo(selectList.get(0));
//                        }
                    }
                    break;
                case REQUEST_CODE:
                    int pos = data.getIntExtra(PictureExternalPreviewActivity.POS, 0);
                    if (pos > 0) {
                        selectList = (List<LocalMedia>) data.getSerializableExtra(PictureExternalPreviewActivity.PIC_LIST);
                        adapter.setData(selectList);
                    } else {
                        adapter.clean();
                        selectList.clear();
                    }
                    break;
                case BRANCH:
                    branchName =data.getStringExtra("branchName");
                    branchId =data.getIntExtra("branchId",0);
                    if(!TextUtils.isEmpty(branchName)) {
                        tv_depart.setText(branchName);
                    }
                    break;
            }
        }
    }
    //默认视频缓存文件夹
    private static final String VIDEO_PATH = Environment.getExternalStorageDirectory().getPath() + PictureFileUtils.CAMERA_VIDEO_PATH;
    /**
     * 切换设置屏幕常亮状态
     * @param isKeep 是否常亮
     */
    private void keepWindowOn(boolean isKeep){
        if(isKeep){
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        }else{
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        }
    }
    /**
     * 压缩视频
     *
     * @param video
     */
    private void compressVideo(LocalMedia video) {
        showProgress("视频处理中，请勿退出或关闭屏幕"  , false);
        keepWindowOn(true);
        isCompressing = true;
        isCompressSuccess = false;
        try {
            File fileNew = new File(VIDEO_PATH);
            if (!fileNew.exists()) {
                fileNew.mkdirs();
            }
            //compress and output new video specs
            new VideoCompressAsyncTask(this,compressHandler).execute(video.getPath(), fileNew.getPath());
        } catch (Exception e) {
            e.printStackTrace();
            keepWindowOn(false);
        }
    }

    private void getShotDiaFragment() {
        if (shotChoiceDiaFragment == null) {
            shotChoiceDiaFragment = new ShotChoiceDiaFragment();
        }
        shotChoiceDiaFragment.setCallBack(shotCallBack);
        shotChoiceDiaFragment.show(getSupportFragmentManager(), SHOT_TAG);
    }

    private BaseDialogFragment.ICallBack rebllionCallback = new BaseDialogFragment.ICallBack() {
        @Override
        public void onCallBackMsg(BaseDialogFragment fragment, Message msg) {
            rebellionType = msg.what;
            // shotChoiceDiaFragment.dismiss();
            refreshRebellionType();
        }
    };

    private void refreshRebellionType() {
        switch (rebellionType) {
            case Constances.REBELLION_TYPE_BREAKING_NEWS:
                type_cv.setText(getString(R.string.rebllion_type_one));
                break;
            case Constances.REBELLION_TYPE_EXPERIENCES:
                type_cv.setText(getString(R.string.rebllion_type_two));
                break;
            case Constances.REBELLION_TYPE_HOT_NEWS:
                type_cv.setText(getString(R.string.rebllion_type_three));
                break;
            case Constances.REBELLION_TYPE_PIC_NEWS:
                type_cv.setText(getString(R.string.rebllion_type_four));
                break;
            case Constances.REBELLION_TYPE_VIDEO_NEWS:
                type_cv.setText(getString(R.string.rebllion_type_five));
                break;
        }
    }

    BaseDialogFragment.ICallBack picCallBack = new BaseDialogFragment.ICallBack() {
        @Override
        public void onCallBackMsg(BaseDialogFragment fragment, Message msg) {
            if (msg.what == 1) {
                if (selectList.size() != 0) {
                    int pictureType = PictureMimeType.isPictureType(selectList.get(0).getPictureType());
                    if (pictureType == 2 && selectList.size() == 1) {
                        toast("只能选择一个视频");
                    } else {
                        getShotDiaFragment();
                    }
                } else {
                    getShotDiaFragment();
                }
            } else if (msg.what == 2) {
                type = TYPE_PIC;
                PictureUtils.choicePic(ApplyCommitActivity.this, themeId, selectList);
            }
        }
    };
    BaseDialogFragment.ICallBack shotCallBack = new BaseDialogFragment.ICallBack() {
        @Override
        public void onCallBackMsg(BaseDialogFragment fragment, Message msg) {
            if (msg.what == 1) {
                type = TYPE_CAMERA_PIC;
                PictureUtils.choicePhoto(ApplyCommitActivity.this);
            } else if (msg.what == 2) {
                type = TYPE_VIDEO;
                if (selectList != null) {
                    selectList.clear();
                }
                PictureUtils.choiceVideo(ApplyCommitActivity.this);
            }
        }
    };
    OnItemInternalClick picItemClick = new OnItemInternalClick() {
        @Override
        public void onItemInternalClick(View itemView, View view, int position) {
            if (selectList == null) {
                return;
            }
            if (position == adapter.getItemCount() - 1) {
                if (selectList.size() < 9) {
                    if (picChoiceDiaFragment == null) {
                        picChoiceDiaFragment = new PicChoiceDiaFragment();
                    }
                    picChoiceDiaFragment.setCallBack(picCallBack);
                    if (!picChoiceDiaFragment.isShowing()) {
                        picChoiceDiaFragment.show(getSupportFragmentManager(), PIC_TAG);
                    }
                    prompt.setVisibility(View.GONE);
                } else {
                    toast(getString(R.string.rebllion_publish_pic_total));
                }

            } else {
                LocalMedia media = adapter.getItem(position);
                String pictureType = media.getPictureType();
                int mediaType = PictureMimeType.pictureToVideo(pictureType);
                switch (mediaType) {
                    case 1:
                        // 预览图片 可自定长按保存路径
                        Intent intent = new Intent(ApplyCommitActivity.this, PictureExternalPreviewActivity.class);
                        intent.putExtra(PictureConfig.EXTRA_PREVIEW_SELECT_LIST, (Serializable) selectList);
                        intent.putExtra(PictureConfig.EXTRA_POSITION, position);
                        intent.putExtra(PictureConfig.DIRECTORY_PATH, "/custom_file");
                        startActivityForResult(intent, REQUEST_CODE);
                        overridePendingTransition(com.luck.picture.lib.R.anim.a5, 0);
                        break;
                    case 2:
                        // 预览视频
                        PictureSelector.create(ApplyCommitActivity.this).externalPictureVideo(media.getPath());
                        break;
                    case 3:
                        // 预览音频
                        PictureSelector.create(ApplyCommitActivity.this).externalPictureAudio(media.getPath());
                        break;
                }
            }
        }
    };

    OnItemInternalClick onLongClick = new OnItemInternalClick() {
        @Override
        public void onItemInternalClick(View itemView, View view, int position) {
            if (isLongClick) {
                adapter.setEdting(true);
                isLongClick = false;
            } else {
                adapter.setEdting(false);
                isLongClick = true;
            }
        }
    };

    @Override
    public void getRemainListSize(List<LocalMedia> list) {
        selectList = list;
        currentList = list;
        adapter.notifyDataSetChanged();
    }


    /**
     * 发表报料内容
     */
    public void uploadData() {
        Cache.getInstance().setUploadReb(true);
        if (currentList.size() > 0) {
            List<String> picList = new ArrayList<>();
            if (PictureMimeType.pictureToVideo(currentList.get(0).getPictureType()) == 1) {
                showProgress(getString(R.string.rebllion_publish_wait), false);
                //如果爆料的是图片内容，直接上传
                for (int i = 0; i < currentList.size(); i++) {
                    if (TextUtils.isEmpty(currentList.get(i).getCompressPath())) {
                        picList.add(currentList.get(i).getPath());
                    } else {
                        picList.add(currentList.get(i).getCompressPath());
                    }
                }
                mCallback.setInt1(1);
                isPublishing = true;
                NetUtils.getNetAdapter().uploadImages1(getOwnerName(), picList, mCallback);
            } else if ((PictureMimeType.pictureToVideo(currentList.get(0).getPictureType()) == 2)) {
                //如果爆料的是视频内容，先压缩再上传
                if (null != currentList && currentList.size() > 0 && !TextUtils.isEmpty(currentList.get(0).getPath())) {
                    if (!TextUtils.isEmpty(compressPath) && isCompressSuccess) {
                        File file = new File(compressPath);
                        if (file.exists()) {
                            uploadVideo();
                            return;
                        }
                    }
                    //压缩视频
                    compressVideo(currentList.get(0));
                }
            }
        } else {
            publish(null, null);
        }
    }

    /**
     * 视频压缩完成之后直接上传
     */
    public void uploadVideo() {
        List<String> picList = new ArrayList<>();
        //视频
        mVideoCoverImage = UIUtils.getFirstFrameFromVideo(compressPath);
        if (TextUtils.isEmpty(mVideoCoverImage)) {
            closeProgress();
            toast(R.string.rebllion_publish_video_cover_path_empty);
            return;
        }
        showProgress(getString(R.string.rebllion_publish_wait), true);
        File file = new File(compressPath);
        long fileSize = LocalUtils.getFileSize(file);
        picList.add(mVideoCoverImage);
        mCallback.setInt1(2);
        mCallback.setObj(compressPath);
        NetUtils.getNetAdapter().uploadImages1(getOwnerName(), picList, mCallback);
    }

    /**
     * 提交 报料内容
     *
     * @param singleResult
     * @param videoCoverImage
     */
    private void publish(SingleResult singleResult, Object videoCoverImage) {
        FUsers fUsers = UserManager.getInstance().getUser();
        ParamsEditor pe = new ParamsEditor();
        pe.put("userId", fUsers.getUserId());
        pe.put("discloseType", rebellionType);
        pe.put("content", rebllion_commit.getText().toString());
        if (mLocationState == 0 || mLocationState == 2) {
            addree_cv.setText("");
        }
        if(null != tp){
            if(tp.getId()>-1) {
                pe.put("topicId", tp.getId());
            }else{
                pe.put("topicId","");
            }

        }
        else {
            pe.put("topicId", "");
        }

        pe.put("branchId", branchId);

        pe.put("topicType", 1);

        pe.put("title", TextUtils.isEmpty(rebllion_commit_title.getText().toString()) ? "" : rebllion_commit_title.getText().toString());
        pe.put("contact", TextUtils.isEmpty(rebllion_commit_contact.getText().toString()) ? "" : rebllion_commit_contact.getText().toString());
        pe.put("isAnonymous", push_cb.isChecked() ? 1: 0);


        pe.put("location", addree_cv.getText().toString());
        pe.put(Constances.SITE_NET_KEY, Constances.SITE_ID);

        pe.put("image", singleResult == null || singleResult.getImages() == null ? "" : singleResult.getImages().toString());
        pe.put("video", singleResult == null || TextUtils.isEmpty(singleResult.getVideoUrl()) ? "" : singleResult.getVideoUrl());
        if (images != null) {
            coverImageUrl = images.get(0).getAsJsonObject().get("imageUrl").getAsString();
        }
        pe.put("coverImage", TextUtils.isEmpty(coverImageUrl) ? "" : coverImageUrl);
        pe.put("siteNumber", Constances.SITE_ID);
        NetUtils.getNetAdapter().postWenzheng(getOwnerName(), pe.getEncryptedParams(fUsers.getToken()), new AbsNetCallBack<RebllionCommitResult>(RebllionCommitResult.class) {
            @Override
            public void onSuc(RebllionCommitResult singleResult) {
                if (singleResult == null) {
                    return;
                }
                toast(R.string.rebllion_publish_succ);
                deleteTempVideo();
                SkipUtil.skipToAddUserOperate(ApplyCommitActivity.this, getOwnerName(),  11, 3, "投稿成功", "" + singleResult.getInfoId(), Cache.getInstance().getCurrentChannelId());
                addInvitation(Constances.ADD_INTEGRAL_SUBMISSION, true);
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
//                toast(R.string.rebllion_publish_failure);
                showPublishFailure();
                closeProgress();
            }

            @Override
            public void onEnd() {
                closeProgress();
                Cache.getInstance().setUploadReb(false);
                keepWindowOn(false);
            }
        });
    }
    /**
     * 上传图片、视频资源的回调，进一步上传整个报料内容
     */
    AbsNetCallBack mCallback = new AbsNetCallBack<SingleResult>(SingleResult.class) {
        @Override
        public void onSuc(SingleResult singleResult) {
            if (singleResult == null || !singleResult.isSuccess() ||
                    (getInt1() == 1 && singleResult.getImages() == null) ||
                    (getInt1() == 2 && (singleResult.getImages() == null || !singleResult.getImages().toString().contains("imageUrl"))) ||
                    (getInt1() == 3 && TextUtils.isEmpty(singleResult.getVideoUrl()))) {
//                onError(null, null);
                return;
            }

            if (getInt1() == 2) {
                String videoUrl = getObj().toString();
                mCallback.setInt1(3);
                images = singleResult.getImages();
                mCallback.setObj(singleResult.getImages().toString());
                deleteVideoCoverImage();
                NetUtils.getNetAdapter().uploadVideo(getOwnerName(), videoUrl, mCallback);
                return;
            }

//            if (getInt1() == -1) {
//                toast(R.string.rebllion_publish_succ);
//                SkipUtil.skipToAddUserOperate(RebllionCommitActivity.this, getOwnerName(), 1, 11, 3, "投稿成功", "", Cache.getInstance().getCurrentChannelId());
//                addInvitation(Constances.ADD_INTEGRAL_SUBMISSION, true);
////                finish();
//                return;
//            }

            if (getInt1() == 1 || getInt1() == 3) {
                //getInt1为1时getObj为空
                publish(singleResult, getObj());
                return;
            }
        }

        @Override
        public void onError(Throwable ex, String errorMsg) {
//            toast(R.string.rebllion_publish_failure);
            showPublishFailure();
            closeProgress();
            Cache.getInstance().setUploadReb(false);
            if (getInt1() == 2) {
                deleteVideoCoverImage();
            }
            isPublishing = false;
            keepWindowOn(false);
        }

        @Override
        public void onEnd() {
            if (getInt1() == -1) {
                closeProgress();
                isPublishing = false;
                Cache.getInstance().setUploadReb(false);
                keepWindowOn(false);
            }
        }
    };

    /**
     * 删除视频临时封面图片
     */
    private void deleteVideoCoverImage() {
        if (!TextUtils.isEmpty(mVideoCoverImage)) {
            File file = new File(mVideoCoverImage);
            if (file.exists()) {
                file.delete();
                mVideoCoverImage = null;
            }
        }
    }

    /**
     * 删除压缩的临时视频文件
     */
    private void deleteTempVideo() {
        if (!TextUtils.isEmpty(compressPath) && isCompressSuccess) {
            File file = new File(compressPath);
            if (file.exists()) {
                file.delete();
            }
        }
        compressPath = "";
    }
    private ConfirmDialogFragment confirmFragment;
    public static final String REPORT_TAG = "report_fragment";

    private void showPublishFailure() {
        if (confirmFragment == null) {
            confirmFragment = new ConfirmDialogFragment();
        }
        confirmFragment.show(getSupportFragmentManager(), REPORT_TAG);

    }




    private void getLocation() {
        mLocationState = 0;
        refreshLocationState(null);
        if (SystemClock.elapsedRealtime() - mLocationTime >= 1000) {
            initLocation();
            mLocationTime = SystemClock.elapsedRealtime();
        } else {
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    initLocation();
                    mLocationTime = SystemClock.elapsedRealtime();
                }
            }, 1000);
        }
    }

    private void locatingFailed(String errorStr) {
        if(locateFailTimes==0) {
            toast(errorStr);
        }

        mLocationState = 2;
        refreshLocationState(null);

        locateFailTimes++;
        if(locateFailTimes<3) {
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    getLocation();
                }
            }, 1000);

        }

    }

    private void refreshLocationState(String location) {
        switch (mLocationState) {
            case 0:
                addree_cv.setText(R.string.rebllion_publish_locating);
                break;
            case 1:
                addree_cv.setText(location);
                break;
            case 2:
                addree_cv.setText(R.string.rebllion_publish_locating_failed);
                break;
        }
    }

    private void checkLocationPermission() {
        mPermissionUtils = new PermissionUtils(this);
        mPermissionUtils.addPermission(Manifest.permission.READ_PHONE_STATE);
        mPermissionUtils.addPermission(Manifest.permission.ACCESS_COARSE_LOCATION);
        mPermissionUtils.addPermission(Manifest.permission.ACCESS_FINE_LOCATION);
        mPermissionUtils.addPermission(Manifest.permission.READ_EXTERNAL_STORAGE);
        mPermissionUtils.addPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);

        mPermissionUtils.setPermissionListener(new PermissionUtils.PermissionListener() {
            @Override
            public void onUserRefusesPermissions() {
                locatingFailed("用户拒绝了权限，定位无法进行, 如需重新授予权限，请进入手机的“设置-应用程序-SiChuanFocus2Android”中打开权限");
            }
        });

        if (mPermissionUtils.checkAndRequestPermissions()) {
            initLocation();
            getLocation();

        } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            locatingFailed("用户拒绝了权限，定位无法进行, 如需重新授予权限，请进入手机的“设置-应用程序-SiChuanFocus2Android”中打开权限");
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PermissionUtils.PERMISSIONS_REQUEST_CODE) {
            String msg = "本页面的定位功能需要用到以下权限：\n1. 读取手机状态\n2. 获取位置信息（基站）\n3. 获取位置信息（GPS）\n4. 读取手机存储的信息\n5. 写入信息到手机存储\n\n请授予这些权限确保定位功能可以正常运行。";
            if (mPermissionUtils.recheckPermissions(grantResults, msg)) {
                initLocation();
                getLocation();
            }
        }
    }

    /**
     * 开始定位
     */
    private void initLocation() {
        GaoDeLocationUtil.getInstance().registerOnLocatedListener(this);
        GaoDeLocationUtil.getInstance().startLocate(ApplyCommitActivity.this);
    }

    @Override
    protected void onDestroy() {
        GaoDeLocationUtil.getInstance().stopLocate();
        isInCurrentPage = false;
        Cache.getInstance().setUploadReb(false);
        super.onDestroy();
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
    }

    @Override
    public void afterTextChanged(Editable s) {
        int length = getStrLength(s.toString());
        if (length == 120) {
            toast(R.string.only_120_word);
        }
    }

    private int getStrLength(String str) {
        if (str == null) {
            return 0;
        }
        return str.length();
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

    }

    private boolean checkPhone() {
        if (TextUtils.isEmpty(rebllion_commit_contact.getText().toString()) || !rebllion_commit_contact.getText().toString().matches(Constances.MATCHER_PHONE)) {
            toast(R.string.please_input_valued_phone);
            return false;
        }
        return true;
    }
    private boolean checkTitle() {
        if (TextUtils.isEmpty(rebllion_commit_title.getText().toString())) {
            toast(R.string.please_input_title);
            return false;
        }else if(rebllion_commit_title.getText().toString().length()<6 || rebllion_commit_title.getText().toString().length()>20){
            toast(R.string.number_warning);
            return false;
        }
        return true;
    }


    @Override
    public void onLocationChange(AMapLocation location) {
        GaoDeLocationUtil.getInstance().unregisterOnLocatedListener(this);
        GaoDeLocationUtil.getInstance().stopLocate();

        String locationStr;

        if (TextUtils.isEmpty(location.getCity()) || TextUtils.isEmpty(location.getDistrict())) {
            locatingFailed("获取定位失败，未知错误");
            return;
        }
        JLog.e("OnLocated", "-R--location =" + location.getCity());
        locationStr = location.getCity() + "-";    //获取城市信息
        locationStr += location.getDistrict();    //获取区县信息
        mLocationState = 1;
        refreshLocationState(locationStr);
    }


    private void showProtocol() {
        if (protocolFragment == null) {
            protocolFragment = new ProtocolFragment();
            Bundle bundle = new Bundle();
            bundle.putString("1", getResources().getString(R.string.protocol_1));
            bundle.putString("2", getResources().getString(R.string.protocol_2));
            bundle.putString("3", getResources().getString(R.string.protocol_3));
            bundle.putString("4", getResources().getString(R.string.protocol_4));
            bundle.putString("title", getResources().getString(R.string.text_rules_item_1));
            protocolFragment.setArguments(bundle);
             }

        if (!protocolFragment.isAdded()) {
            protocolFragment.show(getSupportFragmentManager(),PROTOCOL_TAG);

        }


    }

}
